<template>
  <div class="no-background-container">
    <el-affix :offset="72">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">{{ routeName }}</div>
        </div>
        <div class="header-query">
          <el-button type="primary" @click="showFormDialog = true">新增{{ moduleName }}</el-button>
          <query-form
            :columns="columns"
            :list-loading="listLoading"
            :query-form="queryForm"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <div class="qs-y-table-card">
      <el-table ref="tableSortRef" v-loading="listLoading" border :data="list" stripe @selection-change="setSelectRows">
        <el-table-column align="center" label="序号" width="55">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>

        <el-table-column
          v-for="(item, index) in finallyColumns"
          :key="index"
          align="center"
          :fixed="item.fixed"
          :label="item.label"
          :min-width="item.minWidth || 150"
          :prop="item.prop"
          show-overflow-tooltip
          :sortable="item.sortable"
        >
          <template #default="{ row }">
            <span v-if="item.label === '名称'" @click="handleDetails(row)">
              <div style="font-size: 12px; cursor: pointer">{{ row.contractNo }}</div>
              <div style="font-size: 14px; font-weight: 500; color: var(--el-color-primary); cursor: pointer">{{ row[item.prop] }}</div>
            </span>
            <span v-else-if="item.label === '设备配置'">
              <el-tag v-for="(tag, tagIndex) in row[item.prop]" :key="tagIndex" style="margin-right: 5px">{{ tag }}</el-tag>
            </span>
            <span v-else-if="item.label === '图片'">
              <el-image fit="cover" :src="row[item.prop]" style="width: 50px; height: 50px" />
            </span>
            <span v-else>{{ row[item.prop] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" text @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" text type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty class="vab-data-empty" description="暂无数据" />
        </template>
      </el-table>
      <el-pagination
        background
        :current-page="queryForm.page"
        :layout="layout"
        :page-size="queryForm.limit"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 表单弹窗 -->
    <form-dialog
      v-model="showFormDialog"
      :columns="columns"
      :form-data="form"
      :module-name="moduleName"
      :title="isEditMode ? '编辑' : '新增'"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, onActivated, onBeforeMount, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 模拟数据
const mockData = [
  {
    id: 1,
    name: '会议室A',
    location: '一楼',
    area: 100,
    capacity: 20,
    equipmentTags: ['投影仪', '白板'],
    description: '适合小型会议',
    requiresApproval: '是',
    usageScope: '公司内部',
    isOpen: '是',
    contactNumber: '123456789',
    supportedMeetingTypes: ['内部会议', '培训'],
    bookingRules: '提前一天预约',
    status: '可用',
    contractNo: 'C001',
    imageUrl: 'https://via.placeholder.com/50',
  },
  {
    id: 2,
    name: '会议室B',
    location: '二楼',
    area: 150,
    capacity: 30,
    equipmentTags: ['音响', '视频会议系统'],
    description: '适合大型会议',
    requiresApproval: '否',
    usageScope: '公司内部',
    isOpen: '是',
    contactNumber: '987654321',
    supportedMeetingTypes: ['客户会议', '研讨会'],
    bookingRules: '提前两天预约',
    status: '维护中',
    contractNo: 'C002',
    imageUrl: 'https://via.placeholder.com/50',
  },
  // 添加更多模拟数据...
]

// 新增 form 变量
const form = ref<any>({})

// 编辑行数据
const handleEdit = (row: any) => {
  // 将当前行数据赋值给 form
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}
const updateQueryForm = (newQueryForm: any) => {
  queryForm.value = { ...newQueryForm }
}
// 删除行数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 这里可以添加删除逻辑
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 是否为编辑模式
const isEditMode = ref(false)
//模块名称
const moduleName = '会议室'

// 获取当前路由对象
const route = useRoute()

// 计算属性，获取路由名称
const routeName = computed(() => route.meta.title || '')
// 路由实例
const router = useRouter()

// 表格引用
const tableSortRef = ref<any>(null)

// 表格数据
const list = ref<any>([])

// 加载状态
const listLoading = ref<boolean>(true)

// 分页布局
const layout = ref<string>('total, sizes, prev, pager, next, jumper')

// 总条数
const total = ref<any>(0)

// 选中的行
const selectRows = ref<any>([])
const columns = ref<any>([
  {
    label: '会议室名称',
    prop: 'name',
    minWidth: 300,
    component: 'input',
    required: true,
    placeholder: '请输入会议室名称',
    defaultValue: '会议室A',
    colSpan: 24, // 占据整行
    searchable: true,
  },
  {
    label: '面积 (㎡)',
    prop: 'area',
    minWidth: 100,
    component: 'input',
    required: true,
    placeholder: '请输入会议室面积',
    defaultValue: '100',
    colSpan: 12, // 占据半行
    searchable: false,
  },
  {
    label: '会议室容量',
    prop: 'capacity',
    minWidth: 100,
    component: 'input',
    required: true,
    placeholder: '请输入会议室容量',
    defaultValue: '20',
    colSpan: 12, // 占据半行
    searchable: false,
  },
  {
    label: '设备配置',
    prop: 'equipmentTags',
    minWidth: 200,
    component: 'select',
    multiple: true,
    options: [
      { value: '投影仪', label: '投影仪' },
      { value: '白板', label: '白板' },
      { value: '音响', label: '音响' },
      { value: '视频会议系统', label: '视频会议系统' },
      { value: '无线网络', label: '无线网络' },
    ],
    required: true,
    placeholder: '请选择设备配置',
    defaultValue: ['投影仪', '白板'],
    colSpan: 24, // 占据整行
    searchable: true,
  },
  {
    label: '联系电话',
    prop: 'contactNumber',
    minWidth: 150,
    component: 'input',
    required: false,
    placeholder: '请输入联系电话',
    defaultValue: '123456789',
    colSpan: 12, // 占据半行
    searchable: false,
  },
  {
    label: '位置描述',
    prop: 'location',
    minWidth: 200,
    component: 'input',
    required: false,
    placeholder: '请输入会议室位置',
    defaultValue: '一楼',
    colSpan: 12, // 占据半行
    searchable: false,
  },
  {
    label: '预订规则',
    prop: 'bookingRules',
    minWidth: 300,
    component: 'textarea',
    required: false,
    placeholder: '请输入预订规则',
    defaultValue: '提前一天预约',
    colSpan: 24, // 占据整行
    searchable: false,
  },
  {
    label: '会议室描述',
    prop: 'description',
    minWidth: 300,
    component: 'textarea',
    required: false,
    placeholder: '请输入会议室描述',
    defaultValue: '适合小型会议',
    colSpan: 24, // 占据整行
    searchable: false,
  },
  {
    label: '需要审批',
    prop: 'requiresApproval',
    minWidth: 150,
    component: 'switch',
    options: ['是', '否'],
    required: false,
    defaultValue: '是',
    colSpan: 12, // 占据半行
    searchable: false,
  },
  {
    label: '开放状态',
    prop: 'isOpen',
    minWidth: 100,
    component: 'switch',
    options: ['是', '否'],
    required: false,
    defaultValue: '是',
    colSpan: 12, // 占据半行
    searchable: false,
  },
])
// TODO:switch展示未 select 进行检索

// 显示的列
const checkList = ref<any>([])

// 查询表单
const queryForm = reactive<any>({
  page: 1,
  limit: 20,
  search: '',
  name: '',
  area: '',
  capacity: '',
  equipmentTags: [],
  contactNumber: '',
  location: '',
  bookingRules: '',
  description: '',
  requiresApproval: '',
  isOpen: '',
})

// 最终显示的列
const finallyColumns = computed(() => columns.value.filter((item: any) => checkList.value.includes(item.label)))

// 控制表单弹窗显示
const showFormDialog = ref(false)

const fetchData = async () => {
  listLoading.value = true
  try {
    // 使用模拟数据
    list.value = mockData
    total.value = mockData.length
  } catch (error) {
    console.error('获取合同列表失败:', error)
    // 使用模拟数据
    list.value = mockData
    total.value = mockData.length
  } finally {
    listLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

// 当前页改变
const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

// 更新分页信息并重新获取数据
const updatePagination = (params: any) => {
  Object.assign(queryForm, params)
  fetchData()
}

// 查询数据
const queryData = () => {
  updatePagination({ page: 1 })
  fetchData()
}

// 设置选中的行
const setSelectRows = (value: string) => {
  selectRows.value = value
}

// 查看合同详情
const handleDetails = (row: any) => {
  router.push({
    name: 'ContractsDetails',
    query: {
      id: row.id,
      title: row.name,
    },
  })
}

// 表单提交处理
const handleFormSubmit = (formData: any) => {
  console.log('表单提交的数据:', formData)
  // 这里可以添加提交表单数据的逻辑
  fetchData() // 重新获取数据
}

// 组件激活时刷新表格布局并获取数据
onActivated(() => {
  tableSortRef.value.doLayout()
  fetchData()
})

// 组件挂载前初始化列显示和获取数据
onBeforeMount(() => {
  initializeColumns()
  fetchData()
})

// 初始化列显示
const initializeColumns = () => {
  columns.value.forEach((item: any) => {
    if (!item.noChecked) checkList.value.push(item.label)
  })
}
</script>

<style scoped>
.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}
</style>
